package com.changan.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.changan.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void setKey(String key, String value) {
        //设置基本的key和value
        //redisTemplate.opsForValue().set(key, value);
        //设置过期的key和value
        //redisTemplate.opsForValue().set(key, value, 10, TimeUnit.SECONDS);
        //模拟设置验证码的操作
        value = RandomUtil.randomNumbers(6);
        System.out.println(value);
        stringRedisTemplate.opsForValue().set(key, value, 60, TimeUnit.SECONDS);
    }

    @Override
    public void setKeyUseString(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
        //stringRedisTemplate.opsForValue().
    }

    @Override
    public String getKey(String key) {
        //获取所有的key
        Set keys = redisTemplate.keys("*");
        for (Object o : keys) {
            System.out.println(o);
        }
        //判断是否有这个key
        if (!redisTemplate.hasKey(key)) {
            return "验证码已过期!";
        }
        return stringRedisTemplate.opsForValue().get(key);
    }

    @Override
    public void deleteKey(String key) {
        Boolean delete = redisTemplate.delete(key);
        System.out.println("是否删除成功：" + delete);
        System.out.println(redisTemplate.opsForValue().get(key));
    }

    @Override
    public void incr(String key, Integer number) {
        // 当没有key的时候，默认会自动创建一个key
        Long increment = redisTemplate.opsForValue().increment(key, number);
        System.out.println("自增后的值：" + increment);
    }

    @Override
    public void setList(String key, String value) {
        //left和right决定了插入的顺序,从左往右还是从右往左
        //redisTemplate.opsForList().leftPush(key, value);
        //redisTemplate.opsForList().rightPush(key, value);

        //删除元素
        //Object o = redisTemplate.opsForList().leftPop(key);
        /*Object o = redisTemplate.opsForList().rightPop(key);
        System.out.println(o);*/

        //获取元素
        List<String> stringList = redisTemplate.opsForList().range(key, 0, 2);
        for (String s : stringList) {
            System.out.println(s);
        }

        //获取元素的长度
        Long size = redisTemplate.opsForList().size(key);
        System.out.println("list的长度：" + size);

        //删除元素
        redisTemplate.delete(key);
    }


}
